package itsm.isperp.module.service.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.commons.repository.BaseRepository;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IRole;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.service.IRoleService;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.app.VAppDepartmentUser;
import itsm.isperp.module.dto.app.VAppRoleMenu;
import itsm.isperp.module.dto.project.ProjectDomain.ProjectDomainType;
import itsm.isperp.module.entity.app.AppRole;
import itsm.isperp.module.entity.app.AppUserRole;
import itsm.isperp.module.repository.app.AppRoleMapper;
import itsm.isperp.module.repository.app.AppRoleMenuMapper;
import itsm.isperp.module.repository.app.AppUserRoleMapper;
import itsm.isperp.module.repository.app.VAppRoleMenuMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统角色管理服务类
 * 
 * @author lizx
 * @date 2013-2-16
 * @version V1.0
 */
@Service
public class AppRoleService extends BaseService<AppRole> implements
		IRoleService {

	@Autowired
	protected AppRoleMapper appRoleMapper;

	@Autowired
	protected AppUserService appUserService;

	@Autowired
	protected VAppRoleMenuMapper vAppRoleMenuMapper;

	@Autowired
	protected AppRoleMenuMapper appRoleMenuMapper;

	@Autowired
	protected AppUserRoleMapper appUserRoleMapper;

	@Override
	public BaseRepository<AppRole> getRepository() {
		return this.appRoleMapper;
	}

	@Override
	public IRole findRoleById(String id) {
		return this.getRepository().findOne(id);
	}

	public List<AppRole> findAllRole(String... selectColumns) {

		JqGridRequest roleReq = new JqGridRequest();
		roleReq.isPageable(false);
		roleReq.setSelectColumns(selectColumns);
		roleReq.addFilterRule("status", JqGridFilterRuleOp.eq, "1");
		return this.appRoleMapper.findAllByRequest(roleReq);
	}

	public List<AppRole> findAllRoleLtProjectDomain(ProjectDomainType type,
			String... selectColumns) {

		JqGridRequest roleReq = new JqGridRequest();
		roleReq.isPageable(false);
		roleReq.setSelectColumns(selectColumns);
		roleReq.addFilterRule("data_range", JqGridFilterRuleOp.le,
				type.toString());
		return this.appRoleMapper.findAllByRequest(roleReq);
	}

	@Override
	public List<VAppRoleMenu> findResourceRolesByRole(String roleId) {
		return this.vAppRoleMenuMapper.findByRoleId(roleId);
	}

	@Override
	public List<? extends IRole> findRolesByUsername(String username) {
		return this.appUserService.findMemberRolesByUsername(username);
	}

	/**
	 * 删除角色关联的菜单，角色关联的用户以及角色实体本身
	 */
	@Override
	public ResultMessage delete(String id) {
		// 删除角色菜单
		this.appRoleMenuMapper.deleteByRoleId(id);
		// 删除角色关联的用户
		this.appUserRoleMapper.deleteByRoleId(id);
		// 删除角色实体
		this.appRoleMapper.deleteByClass(id, AppRole.class);
		return ResultMessage.success();
	}

	@Transactional
	public void saveRoleKngCategory(String id, String[] categories) {
		saveRoleResouce(id, "app_role_kng_cagetory", categories);
	}

	/**
	 * 更新或者保存角色实体及角色实体的菜单
	 * 
	 * @param model
	 *            {@link AppRole} 角色实体模型
	 * @param dto
	 *            {@link AppRole} AppRoleMenuDTO 角色&菜单资源
	 */
	@Transactional
	public void saveOrUpdate(AppRole model, String[] menus) {

		if (model == null) {
			throw new NullArgumentException("角色实体不能为空");
		}
		if (StringUtils.isEmpty(model.getId())) {

			String roleId = HibernateUUIDGenerator.generate().toString();

			model.setId(roleId);
			this.saveOrUpdate(model);

		} else {
			this.saveOrUpdate(model);

		}
		saveRoleResouce(model.getId(), "app_role_menu", "app_menu_id", menus);
		// 重新载入系统的权限配置缓存
		ContextHolder.reloadAuthorityResourceDefinition();
	}

	public void saveRoleResouce(String roleId, String roleResouceTable,
			String[] menus) {
		saveRoleResouce(roleId, roleResouceTable, "category_id", menus);

	}
	
	public String getRoleIdByName(String roleName, String userName) {
		String sql="select * from v_app_user_role where app_user_name='"+userName+"' and name='"+roleName+"'";
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
		if(list.size()>0)
		{
			return list.get(0).get("id").toString();
		}
		else
		{
			return null;
		}
	}

	public void saveRoleResouce(String roleId, String roleResouceTable,
			String resouceColumn, String[] menus) {
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		jdbcTemplate.update("DELETE FROM " + roleResouceTable
				+ " WHERE app_role_id='" + roleId + "'");

		if (menus != null && menus.length > 0) {

			String sql = "INSERT INTO " + roleResouceTable
					+ " (id,app_role_id," + resouceColumn + ") VALUES(?,?,?)";

			List<Object[]> list = new ArrayList<>();

			for (String m : menus) {
				Object[] arg = new Object[3];
				arg[0] = HibernateUUIDGenerator.generate();
				arg[1] = roleId;
				arg[2] = m;

				list.add(arg);
			}
			jdbcTemplate.batchUpdate(sql, list);

		}

	}

	/**
	 * 
	 * @param roleId
	 * @param userName
	 * @return
	 */
	public ResultMessage saveRoleUser(String roleId, String userName) {
		List<AppUserRole> list = this.appUserRoleMapper.findAllByRequest(
				new JqGridRequest()
						.isPageable(false)
						.addFilterRule("app_user_name", JqGridFilterRuleOp.eq,
								userName)
						.addFilterRule("app_role_id", JqGridFilterRuleOp.eq,
								roleId)).getContent();

		if (list != null && list.size() > 0) {
			return ResultMessage.newInstance(false, "角色用于已存在");
		}
		AppUserRole ur = new AppUserRole();
		ur.setId(HibernateUUIDGenerator.generate().toString());
		ur.setAppRoleId(roleId);
		ur.setAppUserName(userName);
		this.appUserRoleMapper.save(ur);
		return ResultMessage.success();
	}

	/**
	 * 根据角色Id及用户帐号删除该帐号的角色
	 * 
	 * @param roleId
	 *            角色Id
	 * @param userName
	 *            用户帐号
	 * @return 结果
	 */
	public ResultMessage deleteRoleUser(String roleId, String userName) {
		this.appUserRoleMapper.deleteByUserNameAndRoleId(userName, roleId);
		return ResultMessage.success();
	}

	/**
	 * 获取角色用户数据
	 * 
	 * @param request
	 *            数据请求
	 * @return 角色用户数据请求
	 */
	public PageResponse<VAppDepartmentUser> getRoleUsers(String roleId,
			JqGridRequest request) {

		return this.appUserService.getUserInRole(roleId, request);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * itsm.isperp.framework.service.RoleService#findRoleMembers(java.lang.String
	 * , java.lang.String[])
	 */
	@Override
	public List<Map<String, Object>> findRoleMembers(String roleId,
			String... selectColumns) {
		return this.appUserRoleMapper.findRoleMembersMap(roleId, selectColumns);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * itsm.isperp.framework.service.RoleService#findRoleMembers(java.lang.String
	 * )
	 */
	@Override
	public List<? extends IUser> findRoleMembers(String roleId) {

		return this.appUserRoleMapper.findRoleMembers(roleId, null);
	}

	@Override
	public List<? extends IRole> findAllRoles() {
		return this.appRoleMapper.findAllByRequest(new JqGridRequest()
				.isPageable(false));
	}

}
